package com.estar.integaration.Controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.estar.integaration.Service.*;
import com.estar.integaration.Util.MaterialUtil;
import com.estar.integaration.Util.StreamUtil;
import com.estar.integaration.entity.ChildAcode;
import com.estar.integaration.entity.Material;
import com.estar.integaration.entity.MaterialVo;
import com.estar.integaration.entity.NoSQL.Res;
import com.estar.integaration.entity.ProductionSchedule;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author YJL
 * @since 2021-11-18
 */
@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    IMaterialVoService materialvoService;
    @Autowired
    IMaterialService materialService;
    @Autowired
    IChildAcodeService childAcodeService;
    @Autowired
    IProductDbService productDbService;
    @Autowired
    IProductionScheduleService productionScheduleService;

    @GetMapping("/getFilterMaterial")
    public Res getFilterMaterial(){

        List<Material> materialList = materialService.selectList(null);

        materialList = StreamUtil.filterListUnpurchasedBiggerThanZero(materialList);

        return new Res("20000",new Gson().toJson(materialList));

    }

    @GetMapping("/getAllMaterial")
    public Res getAllMaterial(){

        List<Material> materialList = materialService.selectList(null);

        return new Res("20000",new Gson().toJson(materialList));

    }

    @Autowired
    IMaterialService iMaterialService;

    ArrayList<Material> materialList = new ArrayList<>();

    /**
     * 根据物物料筛选出有效的内容
     * @return
     */
    @GetMapping("/filter")
    public Res FilterData(@RequestParam String content){
        List<Material> materialList  =  materialService.selectList(null);
        if(content.equals("")){
            return new Res("20000",new Gson().toJson(StreamUtil.filterListUnpurchasedBiggerThanZero(materialList)));
        }else {
            return new Res("20000",new Gson().toJson(materialList.stream()
                .filter(
                    x -> {
                    if(content != null){
                        return x.getMaterialNo().contains(content);
                    }else
                        return false;
                    }
                )
                .sorted(Comparator.comparing(Material::getMaterialNo))
                .collect(Collectors.toList())));
        }
    }


    @PostMapping("/sortDelivery")
    public Res sortDelivery(){
        return new Res("20000","");
    }


    /**
     * 筛选出所有需购等于0的
     * @Author  HLF
     */
    @GetMapping("/allPruchased")
    public Res allPurchased() {
        List<Material> pList = materialService.selectList(null);
        pList = StreamUtil.filterListUnpurchasedEQZero(pList);
        return new Res("20000",new Gson().toJson(pList));
    }

    /**
     * 功能： 筛选出库存大于0
     * @Author HLF
     */
    @GetMapping("/inventoryfilter")
    public Res inventoryFilter(){
        //先在数据库出找出所有的物料
        List<Material> pList = materialService.selectList(null);
        pList = StreamUtil.filterListInventoryBiggerThanZero(pList);
        return new Res("20000",new Gson().toJson(pList));
    }

    /**
     * 根据加急筛选出有效的内容，筛选出需购大于0的
     * @return
     */
    @GetMapping("/urgentfilter")
    public Res UrgentFilterData(){
        List<Material>  materialList = materialService.selectList(null);
        return new Res("20000",new Gson().toJson(materialList.stream()
            .filter(
                x->{
                    if(x.getIsUrgent() == null){
                        return false;
                    }
                    return x.getIsUrgent();
                }
            )
            .filter(
                x->{
                    if(x.getUnpurchased() == null){

                        return false;
                    }
                    return x.getUnpurchased() > 0;
                }

            )
            .sorted(Comparator.comparing(Material::getDelivery))
            .collect(Collectors.toList())));
    }

    /**
     * 根据A码筛选出有效的内容
     * @return
     */
    @GetMapping("/Acodefilter")
    public Res ACodeFilterData(@RequestParam String content){
        List<Material> materialList = materialService.selectList(null);
        if(content.equals("")){
            return new Res("20000",new Gson().toJson(StreamUtil.filterListUnpurchasedBiggerThanZero(materialList)));
        }else {
            return new Res("20000",new Gson().toJson(materialList.stream()
                .filter(x -> {
                    if(x.getACode() != null)
                        return x.getACode().contains(content) && x.getUnpurchased() >= 0;
                    return false;
                })
                .sorted(Comparator.comparing(Material::getMaterialNo))
                .collect(Collectors.toList())));
        }
    }

    /**
     * 根据uppurchased字段导出需购<0
     * @return
     */
    @GetMapping("/getHaveFinishedBuy")
    public Res selectPurchaseDepartByUnpurchased(){
        List<Material> pList = materialService.selectList(null);
         pList = pList.stream().filter(x -> x.getUnpurchased() < 0)
        .sorted(Comparator.comparing(Material::getMaterialNo))
        .collect(Collectors.toList());
        return new Res("20000",new Gson().toJson(pList));
    }

    /**
     * 功能：用库存
     */
    @GetMapping("/changeInventory")
    public Res changeInventory(@RequestParam String id,
                               @RequestParam Double thisUse,
                               @RequestParam String inventoryRemark){
        //根据id查找到对应的物料
        Material material = materialService.getOneMaterialById(id);

        UpdateWrapper updateWrapper = new UpdateWrapper();

        updateWrapper.eq("id",id);

        if(thisUse != null){
            //需购数量 = 需购数量-本次使用
            Double newNeedBuy = material.getUnpurchased() - thisUse;
            //库存总数 = 库存总数+本次使用
            Double inventory = material.getInventory() + thisUse;
            //设置为新的需购数量
            updateWrapper.set("unpurchased",newNeedBuy);
            //设置为新的库存
            updateWrapper.set("inventory",inventory);
        }else {
            //数字不动
            Double newNeedBuy = material.getUnpurchased();
            //数字不动
            Double inventory = material.getInventory();
            //设置为新的需购数量
            updateWrapper.set("unpurchased",newNeedBuy);
            //设置为新的库存
            updateWrapper.set("inventory",inventory);
        }
        //将库存备注写入数据库
        updateWrapper.set("inventory_remark",inventoryRemark);
        materialService.updateMaterial(material,updateWrapper);
        return new Res("20000","success");
    }


    @PostMapping("/sort")
    public Res sort(@RequestBody JSONObject jsonObject){
        String sortType = jsonObject.getString("item");
        JSONArray nowListArray = jsonObject.getJSONArray("thislist");
        List<Material> materialList = new LinkedList<>();

        for(int i = 0 ; i < nowListArray.size() ; i++){
            JSONObject tmpJo = nowListArray.getJSONObject(i);
            Material material = MaterialUtil.parseMaterialFromJson(tmpJo);
            materialList.add(material);
        }

        if(sortType.equals("时间递减")){
            materialList = materialList.stream()
                .sorted(new Comparator<Material>() {
                            @Override
                            public int compare(Material o1, Material o2) {
                                if(o1.getDelivery() == null || o2.getDelivery() == null){
                                    return -1;
                                }
                                return o1.getDelivery().compareTo(o2.getDelivery());
                            }
                        }.reversed()
                ).collect(Collectors.toList());

        }else if(sortType.equals("时间递减")){

            materialList = materialList.stream()
                .sorted(new Comparator<Material>() {
                        @Override
                        public int compare(Material o1, Material o2) {
                            if(o1.getDelivery() == null || o2.getDelivery() == null){
                                return -1;
                            }
                            return o1.getDelivery().compareTo(o2.getDelivery());
                        }
                    }
                ).collect(Collectors.toList());

        }else {
            materialList = materialList.stream()
                .sorted(Comparator.comparing(Material::getMaterialNo))
                .collect(Collectors.toList());
        }

        return new Res("20000",new Gson().toJson(materialList));

    }



}
